import moment from 'moment';
import store from '@/store';
import { Constant } from '@/constant';
import { JsUtil } from './js-util';

export class DateUtil {
  static formatMoment(date: moment.Moment, format: string = Constant.DATE): string {
    if (!date) {
      return null;
    }

    if (!moment.isMoment(date)) {
      date = this.toMoment(date);
    }

    return date.format(format);
  }

  static formatDate(date: Date, formatStr: string): string {
    return date ? moment(date).format(formatStr) : null;
  }

  static toMoment(date: string): moment.Moment {
    return date ? moment(date) : null;
  }

  // Convert utc time to user date time
  static toMomentTime(time: string): moment.Moment {
    return time ? moment(new Date(`1970-01-01T${time}+0000`), Constant.TIME) : undefined;
  }

  static utcDateToUserDate(date: Date): string {
    return date
      ? moment(date)
          .utcOffset(store.state['moduleUser'].timezone)
          .format(Constant.DATE_TIME_WITH_TIMEZONE)
      : null;
  }

  static formatDateToUtcDate(date: Date): moment.Moment {
    let symbol = store.state['moduleUser'].timezone.substr(0, 1);
    let minutes = parseInt(store.state['moduleUser'].timezone.substr(1).split(':')[0]) * 60 + parseInt(store.state['moduleUser'].timezone.substr(1).split(':')[1]);

    return date ? moment(date).subtract(parseInt(symbol + minutes), 'm') : null;
  }

  static formatTimeToUtcTime(time: string): string {
    return time
      ? moment(time)
          .utc()
          .format(Constant.TIME)
      : null;
  }

  static formatQueryStartDateTime(startTime: moment.Moment): moment.Moment {
    return startTime ? moment(this.formatMoment(startTime, Constant.QUERY_DATE_TIME)) : null;
  }

  static formatQueryEndDateTime(endTime: moment.Moment): moment.Moment {
    if (!endTime) {
      return null;
    }

    let cloneEndTime = moment(JsUtil.deepCopy(endTime))
      .add(1, 'days')
      .toDate();
    return moment(this.formatMoment(moment(cloneEndTime), Constant.QUERY_DATE_TIME));
  }
}

export default DateUtil;
